package com.example.scgw.benchmark.route;

import java.util.List;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author Aaron
 */
@Component
public class MongoRouteDefinitionRepository implements RouteDefinitionRepository {

  private final MongoRouteRepository mongoRouteRepository;

  public MongoRouteDefinitionRepository(MongoRouteRepository mongoRouteRepository) {
    this.mongoRouteRepository = mongoRouteRepository;
  }


  @Override
  public Flux<RouteDefinition> getRouteDefinitions() {
    return mongoRouteRepository.findAll()
        .map(r -> (RouteDefinition) r)
        .doOnComplete(() -> {
          System.out.println("路由加载完成!");
        });
  }

  @Override
  public Mono<Void> save(Mono<RouteDefinition> route) {
    return route.flatMap(
        r -> mongoRouteRepository.save(MongoRouteDefinition.from(r))
            .and(Mono.empty())
    );
  }

  public Mono<MongoRouteDefinition> save(MongoRouteDefinition route) {
    return mongoRouteRepository.save(route);
  }

  @Override
  public Mono<Void> delete(Mono<String> routeId) {
    return routeId.flatMap(mongoRouteRepository::deleteById);
  }

  public Mono<Void> delete(String routeId) {
    return mongoRouteRepository.deleteById(routeId);
  }

  public Flux<MongoRouteDefinition> saveAll(Flux<RouteDefinition> routes) {
    return mongoRouteRepository
        .saveAll(routes.map(MongoRouteDefinition::from));
  }

  public Flux<MongoRouteDefinition> saveAll(List<MongoRouteDefinition> routes) {
    return mongoRouteRepository.saveAll(routes);
  }

  public Mono<Void> deleteAll() {
    return mongoRouteRepository.deleteAll();
  }
}
